# -*- coding: utf-8 -*-
"""
Spyder Editor

This temporary script file is located here:
C:\Documents and Settings\Andrzej\.spyder2\.temp.py
"""

import os
import re 
import numpy as np
import matplotlib.pyplot as plt
from Arduino import Mo
import time

#os.chdir('E:\home\data')
#print os.getcwd()
#file_list = os.listdir(os.getcwd())
#print file_list

def runmo(mode=4, speed=4000, delay=2000):
    
    M = Mo()
    M.open()
    cmd = "set 1 %d" % speed
    M.send(cmd)
    time.sleep(1)
    response = M.query(cmd="run %d %d" % (mode, delay), expected_text="</run>", tag="run")
    M.close()
    print response
    print "Run finished"
    
    if mode == 9:
        filename = 'modata.txt'
        fid = open(filename,'w');fid.write(response);fid.close()
        a = np.genfromtxt(filename,int)
        
        plt.subplot(411)
        plt.contourf(a[:,0:6].transpose(),255)
        plt.xlim(128,a.shape[0])
        
        plt.subplot(412)
        plt.plot(a[:,8])
        plt.plot(a[:,9])
        plt.plot(a[:,10])
        plt.xlim(128,a.shape[0])
        
        plt.subplot(413)
        plt.plot(a[:,12])
        plt.plot(a[:,13])
        plt.xlim(128,a.shape[0])
        
        plt.subplot(414)
        plt.plot(a[:,14])
        plt.plot(a[:,15])
        plt.plot(a[:,16])
        plt.xlim(128,a.shape[0])
        plt.show()
        return a
    elif mode == 4:
        var = np.array(map(int,response.split()))
        acquiering = var == 0
        tracking   = var == 1
        sharp_l    = var == 2
        sharp_r    = var == 3
        line_break = var == 4
        crossing   = var == 5
        all_stop   = var == 6
        acute_l    = var == 7
        acute_r    = var == 8
         
        n = np.arange(len(var))
        plt.plot(n[acquiering],var[acquiering],'-g')
        plt.plot(n[tracking],var[tracking],'-g')
        plt.plot(n[sharp_l],var[sharp_l],'-b')
        plt.plot(n[sharp_r],var[sharp_r],'-k')
        plt.plot(n[line_break],var[line_break],'-r')
        plt.show()         
    else:
        var = map(int,response.split())     
        plt.plot(var,'o')
        plt.show()
    return var
    
